package com.cw.demo.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * netty客户端
 *
 * @author chenw
 * @date 2021/1/7
 */
@Slf4j
public class DemoClient {
    private String serverIp;
    private int serverPort;
    //用于业务处理的计算流程
    private int workerThreads;

    public DemoClient(String serverIp, int serverPort, int workerThreads) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.workerThreads = workerThreads;
    }

    public void start() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(workerThreads);
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline channelPipeline = socketChannel.pipeline();
                        channelPipeline.addLast(new StringEncoder());
                        channelPipeline.addLast(new StringDecoder());
                        channelPipeline.addLast(new DemoClientHandler());
                    }
                });
            bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture channelFuture = bootstrap.connect(serverIp, serverPort)
                .sync();
            channelFuture.channel()
                .writeAndFlush("你好服务端，我是netty客户端");
            channelFuture.channel()
                .closeFuture()
                .sync();
        } catch (Exception e) {
            log.error("客户端异常:{}", e);
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        DemoClient demoClient = new DemoClient("127.0.0.1", 8090, 1);
        demoClient.start();
    }
}
